package logic

import (
	"accu-manage/Pkg"
	"accu-manage/accurpc/accurpc"
	"accu-manage/accurpc/internal/svc"
	"accu-manage/cache"
	"accu-manage/model"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *accurpc.RegisterRequest) (*accurpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if in.SendSms != result {
		return nil, fmt.Errorf("图形验证码错误，请重新输入")
	}
	data, _ := cache.Rdb.Get(l.ctx, "captcha"+in.Tel).Result()
	if in.Captcha != data {
		return nil, fmt.Errorf("验证码错误,请重新输入")
	}
	var findUser model.User
	model.DB.Debug().Where("tel=?", in.Tel).Find(&findUser)
	if findUser.ID != 0 {
		return nil, fmt.Errorf("当前账号已注册，请登录")
	}

	user := model.User{

		Tel:      in.Tel,
		Password: Pkg.Md5Str(in.Password),
	}
	model.DB.Debug().Create(&user)
	return &accurpc.RegisterResponse{
		UserId: int64(user.ID),
	}, nil
}
